﻿using System;
using System.Collections.ObjectModel;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Ink;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Media.Imaging;
using System.Windows.Shapes;
using System.Windows.Threading;
using GalaSoft.MvvmLight.Command;
using JustinAngel.Neurons.Framework;
using JustinAngel.UnitedNationsNews.CustomControls;
using JustinAngel.UnitedNationsNews.Framework;
using JustinAngel.UnitedNationsNews.ItemViewMoels;
using JustinAngel.UnitedNationsNews.Services;
using Microsoft.SilverlightMediaFramework.Core;
using Microsoft.SilverlightMediaFramework.Core.Media;
using Microsoft.SilverlightMediaFramework.Plugins.Primitives;
using Ninject;

namespace JustinAngel.UnitedNationsNews.Pages.Video
{
    public class VideoAndRadioViewModel : VViewModelBase
    {
        public VideoItemViewModel Video { get { return (VideoItemViewModel)Data; } }
        public bool IsVideo { get { return Data is VideoItemViewModel; } }

        public RadioItemViewModel Radio { get { return (RadioItemViewModel)Data; } }
        public bool IsRadio { get { return Data is RadioItemViewModel; } }


        public override void OnDataSet()
        {
            IsMediaBarVisible = true;
            _poster = null;
            IsPosterVisible = false;
            IsMediaLoading = true;
            PlayerSourceUri = null;

            if (!_wasPlaybackPositionRestoredFromZombification)
            {
                CurrentPlaybackPosition = TimeSpan.FromMilliseconds(0);
            }
            else
            {
                _wasPlaybackPositionRestoredFromZombification = false;
            }

            if (IsVideo)
                BeginInvokeOnUIThreadAtEndOfQueue(PlayVideoFromRawDataAndWriteToZuneHub);
            else if (IsRadio)
                DispatcherTimerHelper.On(TimeSpan.FromMilliseconds(300), () => PlayerSourceUri = Radio.Mp3Uri);

            if (IsRadio)
            {
                InitializePoster();
            }

            WriteZunePlay();
        }



        private void InitializePoster()
        {
            _posterNumber = 0;
            _posterTimer = new DispatcherTimer() { Interval = TimeSpan.FromMinutes(1) };
            _posterTimer.Tick += (s, args) => SetPoster();
            SetPoster();
        }


        private void PlayVideoFromRawDataAndWriteToZuneHub()
        {
            
        }

       
        private void OnYouTubeFailure(Exception error)
        {
            if (error == null) return;
            DialogService.ShowMessageBox("We couldn't play this video. Please try again later.",
                                         "We're sorry",
                                        MessageBoxButton.OK);
        }

        [Inject]
        public IDialogService DialogService { get; set; }

        [Inject]
        public INetworkStatusProvider NetworkStatusProvider { get; set; }


        private bool _isLoading;
        public bool IsMediaLoading
        {
            get { return _isLoading; }
            set
            {
                _isLoading = value;
                RaisePropertyChangedAndUpdateVSM(() => IsMediaLoading, value);
            }
        }

        private Uri _playerSourceUri;
        public Uri PlayerSourceUri
        {
            get { return _playerSourceUri; }
            set
            {
                if (IsInEmulator && value != null && !value.OriginalString.EndsWith("mp3"))
                {
                    //if (IsVideo && Video.YouTubeUrl.OriginalString  == "http://www.youtube.com/watch?v=nMOID72aeA0&feature=youtube_gdata")
                    //{
                    //    _playerSourceUri = new Uri("/UNNewsDemoReel.wmv", UriKind.Relative);
                    //}
                    //else
                    //{
                        _playerSourceUri = new Uri("http://cdn2.newsy.com/files/3613_wmv_12880484305.wmv");
                    //}
                }
                else
                {
                    _playerSourceUri = value;
                }
                RaisePropertyChanged(() => PlayerSourceUri);
                RaisePropertyChanged(() => Playlist);
            }
        }

        public ObservableCollection<PlaylistItem> Playlist
        {
            get
            {
                return new ObservableCollection<PlaylistItem>()
                       {
                           new PlaylistItem()
                               {
                                   Title = this.Title,
                                   MediaSource = this.PlayerSourceUri
                               }
                       };
            }
        }

        public string Title
        {
            get
            {
                if (IsVideo)
                    return Video == null ? string.Empty : Video.Title;
                else
                    return Radio == null ? string.Empty : Radio.Title;
            }
        }

        public ICommand PlayStateChangedCommand
        {
            get
            {
                return new RelayCommand<CustomEventArgs<MediaPluginState>>(e =>
                {
                    if (e.Value == MediaPluginState.Playing)
                    {
                        IsMediaLoading = false;
                        IsMediaBarVisible = IsVideo ? false : true;
                        IsPosterVisible = IsRadio;

                    }
                    if (e.Value == MediaPluginState.Playing || e.Value == MediaPluginState.Buffering)
                    {
                        if (CurrentPlaybackPosition.TotalMilliseconds != 0)
                        {
                            MessengerInstance.Send(new SetVideoPlayerCurrentPlaybackPositionMessage(CurrentPlaybackPosition));
                            CurrentPlaybackPosition = TimeSpan.FromMilliseconds(0);
                        }
                    }
                    if (e.Value == MediaPluginState.Buffering)
                    {
                        IsMediaLoading = true;
                    }
                });
            }
        }

        private bool _isMediaBarVisible;
        public bool IsMediaBarVisible
        {
            get { return _isMediaBarVisible; }
            set
            {
                _isMediaBarVisible = value;
                RaisePropertyChanged(() => IsMediaBarVisible);
            }
        }

        public TimeSpan CurrentPlaybackPosition { get; set; }

        private ImageSource _poster = null;
        public ImageSource Poster
        {
            get { return _poster; }
            set
            {
                _poster = value;
                RaisePropertyChanged(() => Poster);
            }
        }

        private DispatcherTimer _posterTimer = null;
        private int _posterNumber = 0;
        private void SetPoster()
        {

            _posterNumber++;
            if (_posterNumber > 7)
                _posterNumber = 1;

            Poster = new BitmapImage(new Uri("/Pages/Video/RadioAssets/UNNewsRadio" + _posterNumber + ".jpg",
                                        UriKind.Relative));

            if (_posterTimer.IsEnabled)
            {
                _posterTimer.Stop();
            }
            _posterTimer.Start();
        }

        public ICommand ChangePoster
        {
            get
            {
                return new RelayCommand(SetPoster);
            }
        }

        private bool _isPosterVisible = false;
        public bool IsPosterVisible
        {
            get { return _isPosterVisible; }
            set
            {
                _isPosterVisible = value;
                RaisePropertyChangedAndUpdateVSM(() => IsPosterVisible, value);
            }
        }

        [Inject]
        public IZuneMediaHubIntegrationService ZuneMediaHubIntegrationService { get; set; }

        [Inject]
        public IIsolatedStorageHelper IsolatedStorageHelper { get; set; }

        private void WriteZunePlay()
        {
            if (IsVideo)
            {
                if (Video.IsNowPlayingRestore)
                {
                    CurrentPlaybackPosition = TimeSpan.FromSeconds(Convert.ToDouble(IsolatedStorageHelper.GetSetting("LastPlaybackPositionTotalSeconds")));
                }

                if (Video.IsNowPlayingRestore || Video.IsHistoryTileRestore)
                {
                    return;
                }

                if (ZuneMediaHubIntegrationService != null) // tombstoning hell
                    ZuneMediaHubIntegrationService.PlayingItem(
                        new ZuneHistoryItem(Video.Title,
                                            "U.N. News",
                                            Video.ImageUri.OriginalString,
                                            Video.YouTubeUrl.OriginalString,
                                            "IsVideo"));


            }
            else if (IsRadio)
            {
                if (Radio.IsNowPlayingRestore)
                {
                    CurrentPlaybackPosition = TimeSpan.FromSeconds(Convert.ToDouble(IsolatedStorageHelper.GetSetting("LastPlaybackPositionTotalSeconds")));
                }

                if (Radio.IsNowPlayingRestore || Radio.IsHistoryTileRestore)
                {
                    return;
                }

                if (ZuneMediaHubIntegrationService != null) // tombstoning hell
                    ZuneMediaHubIntegrationService.PlayingItem(
                    new ZuneHistoryItem(Radio.Title,
                        Radio.Title /*"U.N. News"*/,
                        "/Pages/Video/UNRadioZuneIcon.jpg",
                        Radio.Mp3Uri.OriginalString,
                        "IsRadio"));
            }
        }

        public override void OnBackkeyPress(System.ComponentModel.CancelEventArgs cancelEventArgs)
        {
            if ((IsRadio && (Radio.IsHistoryTileRestore || Radio.IsNowPlayingRestore))
                || (IsVideo && (Video.IsHistoryTileRestore || Video.IsNowPlayingRestore)))
            {
                throw new ApplicationExitException();
            }
        }

        protected override void OnApplicationDeactivated(Neurons.Framework.Messages.ApplicationDeactivatedMessage obj)
        {
            base.OnApplicationDeactivated(obj);

            if (IsVideo)
            {
                WriteStateForProperty("Video", Video);
            }
            else if (IsRadio)
            {
                WriteStateForProperty("Radio", Radio);
            }
        }

        private bool _wasPlaybackPositionRestoredFromZombification = false;
        protected override void CheckOnApplicationActivated()
        {
            if (CanReadStateForProperty("CurrentPlaybackPosition"))
            {
                _wasPlaybackPositionRestoredFromZombification = true;
                CurrentPlaybackPosition = TimeSpan.FromSeconds(ReadStateForProperty<double>("CurrentPlaybackPosition"));
            }

            if (CanReadStateForProperty("Video"))
            {
                Data = ReadStateForProperty<VideoItemViewModel>("Video");
            }
            else if (CanReadStateForProperty("Radio"))
            {
                Data = ReadStateForProperty<RadioItemViewModel>("Radio");
            }

            base.CheckOnApplicationActivated();
        }

        protected override bool IsAutomaticallyTombstoneAndRestoreViewModel
        {
            get
            {
                return false;
            }
        }

        public ICommand MediaEnded
        {
            get
            {
                return new RelayCommand(() => BeginInvokeOnUIThreadAtEndOfQueue(() =>
                    IsMediaBarVisible = true));
            }
        }
    }
}
